package ru.uskov.trainer.datastore.impl;
/*PersistenceManager pm = PMF.get().getPersistenceManager();
Transaction tx = pm.currentTransaction();
try {
  
} catch (Exception e) {
  if (tx.isActive()) {
    tx.rollback();
  }
}*/

import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import ru.uskov.trainer.datastore.IUser;
import ru.uskov.trainer.datastore.PMF;
import ru.uskov.trainer.datastore.UserIdentifyer;
import ru.uskov.trainer.model.UserAuthData;

public class Context extends AbstractContext {

  // private final Map<String, IUser> users;

  // private volatile int maxUserId;

  Context() throws IOException {

    // users = new HashMap<String, IUser>();
  }

  @Override
  public UserAuthData generateNewUserId() {
    Random rnd = new Random(System.currentTimeMillis());
    long start = System.currentTimeMillis();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      UserIdentifyer uid = pm.makePersistent(new UserIdentifyer("" + rnd.nextInt(10000000)));
      return new UserAuthData(uid);
    } finally {
      pm.close();
      System.out.println("***Adding new user id took: " + (System.currentTimeMillis() - start));
    }
  }

  @Override
  public IUser getUserData(UserAuthData userId) {
    long start = System.currentTimeMillis();
    PersistenceManager pm = PMF.get().getPersistenceManager();
    Transaction tx = pm.currentTransaction();
    try {
      tx.begin();
      @SuppressWarnings("unchecked")
      List<User> uid = (List<User>) pm.newQuery("select from " + User.class.getName() + " where id==\"" + userId.getId() + "\"").execute();
      if (uid.size() == 1) {
        tx.commit();
        System.out.println("***1Getting info int Context.class took: " + (System.currentTimeMillis() - start));
        return uid.get(0);
      } else {
        User user = new User(userId.getId());
        pm.makePersistent(user);
        tx.commit();
        System.out.println("***2Getting info int Context.class took: " + (System.currentTimeMillis() - start));
        return user;
      }
    } catch (Exception e) {
      if (tx.isActive()) {
        tx.rollback();
      }
      e.printStackTrace();
      throw new RuntimeException("Not implemented");
    }
  }

  @Override
  public boolean userIdIsCorrect(Long id, String pwd) {
    long start = System.currentTimeMillis();
    if (id == null || pwd == null) {
      return false;
    }
    // TODO use memcache!
    PersistenceManager pm = PMF.get().getPersistenceManager();
    try {
      String queue = "select from " + UserIdentifyer.class.getName() + " where id==" + id;
      @SuppressWarnings("unchecked")      
      List<UserIdentifyer> result = (List<UserIdentifyer>) pm.newQuery(queue).execute();
      if (result.size() == 1) {
        return pwd.equals(result.get(0).getPwd());
      }
      return false; 
    } finally {
      pm.close();
      System.out.println("***Validation of user id took: " + (System.currentTimeMillis() - start));
    }

  }

  

}
